#!/bin/env/python3
from flask import current_app, jsonify, render_template, abort, session, g, request

from . import news_blueprint
from ... import db
from ...models import News, User, Comment, CommentLike
from ...utils.commons import user_login_data
from ...utils.response_code import RET


@news_blueprint.route('/followed_user', methods=['POST'])
@user_login_data
def followed_user():
    if not g.user:
        return jsonify(errno=RET.USERERR, errmsg="用户未登录")
    action = request.json.get("action")
    user_id = request.json.get("user_id")
    if not all([action, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    if not action in ["follow", 'unfollow']:
        return jsonify(errno=RET.DATAERR, errmsg="无效操作")
    try:
        author = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取作者失败")
    if not author:
        return jsonify(errno=RET.NODATA, errmsg="作者不存在")
    if action == "follow":
        # 判断当前用户是否关注:
        if g.user not in author.followers:
            author.followers.append(g.user)
    else:
        if g.user in author.followers:
            author.followers.remove(g.user)
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blueprint.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    if not g.user:
        return jsonify(errno=RET.USERERR, errmsg="用户位登录")
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")

    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    if action not in ["add", "remove"]:
        return jsonify(errno=RET.DATAERR, errmsg="无效操作")

    try:
        com = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取评论失败")
    try:
        if action == "add":
            comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                    CommentLike.user_id == g.user.id).first()
            if not comment_like:
                comment_like = CommentLike()
                comment_like.user_id = g.user.id
                comment_like.comment_id = comment_id

                # 添加到数据库
                db.session.add(comment_like)
                # 评论的点赞数量+1
                com.like_count += 1
                db.session.commit()

            else:
                # 删除点赞
                db.session.delete(comment_like)

                # 评论的点赞数量-1
                if com.like_count > 0:
                    com.like_count -= 1
                db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blueprint.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    if not g.user:
        return jsonify(errno=RET.USERERR, errmsg="用户未登录")
    data = request.json
    news_id = data.get("news_id")
    content = data.get("comment")
    parent_id = request.json.get("parent_id")
    if not all([news_id, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")
    # 创建评论对象
    com = Comment()
    com.user_id = g.user.id
    com.news_id = news_id
    com.content = content
    if parent_id:
        com.parent_id = parent_id
    try:
        db.session.add(com)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据提交失败")
    return jsonify(errno=RET.OK, errmsg="评论成功", data=com.to_dict())


@news_blueprint.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    if not g.user:
        return jsonify(errno=RET.USERERR, errmsg="用户未登录")
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.DATAERR, errmsg="操作类型有误")

    # 取出新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻获取失败")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")

    if action == "collect":
        if news not in g.user.collection_news:
            g.user.collection_news.append(news)

    else:
        if news in g.user.collection_news:
            g.user.collection_news.remove(news)

    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blueprint.route('/<int:news_id>', methods=['GET'])
@user_login_data
def news_details(news_id):
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
    if not news:
        abort(status=404)

    # 获取6条热门新闻
    try:
        new_top = News.query.order_by(News.clicks.desc()).limit(6).all()
    except Exception as e:
        current_app.logger.error(e)
    click_list = []
    for new in new_top:
        click_list.append(new.to_dict())
    # 判断用户是否收藏：
    is_collected = False
    if g.user:
        if news in g.user.collection_news:
            is_collected = True
    # 查询所有的评论内容
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取评论失败")
    comments_list = []
    for comment in comments:
        comm_dict = comment.to_dict()
        # 添加key，value 记录点赞
        comm_dict["is_like"] = False
        # print(comm_dict)
        # 判断用户是否对评论点过赞
        if g.user:
            try:
                comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id).all()

            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg="获取点赞失败")
            user_comment_Like = [like.comment_id for like in comment_like]
            if comment.id in user_comment_Like:
                comm_dict["is_like"] = True
        comments_list.append(comm_dict)

    # 判断用户是否关注了新闻的作者
    is_followed = False
    if g.user and news.user:
        if g.user in news.user.followers:
            is_followed = True
    data = {
        "news_info": news.to_dict(),
        "user_info": g.user.to_dict() if g.user else "",
        "news": click_list,
        "is_collected": is_collected,
        "comments": comments_list,
        "is_followed": is_followed
    }
    return render_template('news_/detail.html', data=data)
